
<template>
  <div class="department-container">
    <div class="app-container">
      <el-card>
        <!-- 用一个行列布局 -->
        <el-row type="flex" justify="space-between" align="middle" style="height: 40px">
          <el-col :span="20">
            <span>江苏传智播客教育科技股份有限公司</span>
          </el-col>
          <el-col :span="4">
            <el-row type="flex" justify="end">
              <!-- 两个内容 -->
              <el-col>负责人</el-col>
              <el-col>操作</el-col>
            </el-row>
          </el-col>
        </el-row>
        <!-- 放置一个el-tree组件 -->
        <el-tree
          :data="list"
          :props="defaultProps"
          :default-expand-all="true"
        >  <!-- 作用域插槽 data拿到的是每一个子节点的对象 -->
          <!--
      什么时候用到作用域插槽？父组件中如果想使用子组件中的数据进行自定义内容的渲染 (table 单元格数据渲染)
    -->
          <template #default="{ data }">
            <el-row
              type="flex"
              justify="space-between"
              align="middle"
              style="height: 40px; width: 100%;"
            >
              <el-col :span="20">
                <span>{{ data.name }}</span>
              </el-col>
              <el-col :span="4">
                <el-row type="flex" justify="end">
                  <!-- 两个内容 -->
                  <el-col>{{ data.manager }}</el-col>
                  <el-col>
                    <!-- 下拉菜单 element -->
                    <el-dropdown>
                      <span>操作<i class="el-icon-arrow-down" /> </span>
                      <!-- 下拉菜单 -->
                      <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item @click.native="PID(data.pid,data.id)">添加子部门</el-dropdown-item>
                        <el-dropdown-item @click.native="edit(data.id)">编辑部门</el-dropdown-item>
                        <el-dropdown-item @click.native="delPart(data.id)">删除部门</el-dropdown-item>
                      </el-dropdown-menu>
                    </el-dropdown>

                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-tree>
      </el-card>

    </div>
    <!-- 添加子部门 -->
    <el-dialog title="添加子部门" :visible="dialogFormVisible" @close="dialogFormVisible = false">
      <el-form ref="addParts" :rules="rules" :model="form">
        <el-form-item label="部门编码" prop="code" :label-width="formLabelWidth">
          <el-input v-model="form.code" autocomplete="off" />
        </el-form-item>

        <el-form-item label="负责人名称" prop="manager" :label-width="formLabelWidth">
          <el-select v-model="form.manager" placeholder="请选择部门负责人">
            <el-option v-for=" item in principal" :key="item.id" :label="item.username" :value="item.username" />
          </el-select>
        </el-form-item>
        <el-form-item label="部门名称" prop="name" :label-width="formLabelWidth">
          <el-input v-model="form.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="部门介绍" prop="introduce" :label-width="formLabelWidth">
          <el-input v-model="form.introduce" autocomplete="off" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click.native.prevent="addPart">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 编辑子部门 -->
    <el-dialog title="添加子部门" :visible="dialogEditVisible" @close="dialogEditVisible = false">
      <el-form ref="addParts" :rules="rules" :model="edits">
        <el-form-item label="负责人名称" prop="manager" :label-width="formLabelWidth">
          <el-select v-model="edits.manager" placeholder="请选择部门负责人">
            <el-option v-for=" item in principal" :key="item.id" :label="item.username" :value="item.username" />
          </el-select>
        </el-form-item>
        <el-form-item label="部门名称" prop="name" :label-width="formLabelWidth">
          <el-input v-model="edits.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="部门介绍" prop="introduce" :label-width="formLabelWidth">
          <el-input v-model="edits.introduce" autocomplete="off" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click.native.prevent="eddPart(edits.id)">确 定</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import { departments, delDepartment, getPrincipal, addDepartment, editDepartment, getEditDepartment } from '@/api/departments'
import { tranListToTreeData } from '@/utils/index'
// 导入局部组件必须在scrip里面导入,在App里面导入
export default {
// 组件名称
  name: 'Department',
  // 接收局部注册的组件
  components: {},
  // 组件参数接收来自父组件的数据
  props: {},
  // 组件数据
  data () {
    const checkName = (rule, value, callback) => {
      if (value < 3) {
        return callback(new Error('名字应大于两个字'))
      } else {
        callback()
      }
    }
    // 部门编码不能重复
    const checkCode = (rule, value, callback) => {
      if (this.code.includes(value) || value.length > 100 || value.length < 1) {
        // console.log(item)
        return callback(new Error('部门编码不能重复且应该是1-100位'))
      } else {
        callback()
      }
    }
    return {
      // 依赖一份树形数据
      list: [], // 处理过的数据
      principal: [], // 负责人
      edits: {}, // 编辑数据
      lists: [], // 线型数据
      code: [], // 所有的code
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      // 添加子部门
      dialogFormVisible: false,
      dialogEditVisible: false, // 编辑部门
      form: {
        code: '',
        introduce: '',
        manager: '',
        name: '',
        pid: ''
      },
      formLabelWidth: '120px',
      // 添加子部门验证
      rules: {
        code: [
          { required: true, message: '请输入部门编码', trigger: 'blur' },
          { validator: checkCode, trigger: 'blur' }
        ],

        manager: [
          { required: true, message: '负责人名字', trigger: 'blur' },
          { validator: checkName, trigger: 'blur' }
        ],
        name: [
          { required: true, message: '部门名称', trigger: 'blur' },
          { min: 2, max: 10, message: '请输入2-10的部门名称', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '部门介绍', trigger: 'blur' },
          { min: 1, max: 100, message: '请输入1-100的部门介绍', trigger: 'blur' }]
      }
    }
  },
  mounted () {
    // 调封装接口的方法获得公司结构
    this.getDepartments()
  },
  methods: {
    // 调接口获得公司结构
    async getDepartments () {
      const req = await departments()
      // console.log(req.data.depts)
      // 深拷贝
      this.lists = JSON.parse(JSON.stringify(req.data.depts))
      // 获得所有code
      this.codes()
      // 转树形结构
      this.list = tranListToTreeData(req.data.depts)
      // 负责人
      const principal = await getPrincipal()
      this.principal = principal.data
      // console.log(this.principal)
    },
    // 取消
    cancel () {
      this.dialogEditVisible = false
      this.dialogFormVisible = false
      this.$refs.addParts.resetFields()
      this.edits = {}
    },
    // 获得所有code
    codes () {
      // console.log(this.lists)
      this.lists.forEach(item => {
        this.code.push(item.code)
      })
    },
    // 点击添加子部门 设置pid
    PID (pid, id) {
      if (pid && id) {
        // 子节点增加子节点
        this.form.pid = id
      } else if (!pid && id) {
        // 根节点增加子节点
        this.form.pid = id
      }
      this.dialogFormVisible = true
    },
    // 新增
    addPart () {
      // 兜底校验
      this.$refs.addParts.validate(async (valid) => {
        if (valid) {
          this.dialogFormVisible = false
          await addDepartment(this.form)
          // 清空form里面的值
          for (const key in this.form) {
            this.form[key] = ''
          }
          this.$refs.addParts.resetFields()
          // 调封装接口的方法获得公司结构
          this.getDepartments()
        }
      })
    },
    // 删除
    delPart (id) {
      this.$confirm('确定删除该部门吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 删除接口
        await delDepartment(id)
        // 调封装接口的方法获得公司结构
        this.getDepartments()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {

      })
    },

    // 修改部门
    edit (id) {
      // console.log(id) 获得当前部门详情
      getEditDepartment(id).then(res => {
        this.edits = res.data
        this.dialogEditVisible = true
      })
    },
    // eddPart 修改 发送请求
    eddPart (id) {
      this.$refs.addParts.validate((valid) => {
        if (valid) {
          // 发送请求
          editDepartment(id, this.edits).then(req => {
            // 调封装接口的方法获得公司结构
            this.getDepartments()
            this.dialogEditVisible = false
            this.edits = {}
            this.$refs.addParts.resetFields()
          }).catch(err => {
            console.log(err)
          })
        }
      })
    }
  }
}
</script>
<style lang='less' scoped>

</style>
